/*
 * ************************************************************************
 *
 *  Copyright © 2018 KYE Company
 *  跨越速运集团有限公司版权所有
 *
 *  PROPRIETARY RIGHTS of KYE Company are involved in the
 *  subject matter of this material. All manufacturing, reproduction, use,
 *  and sales rights pertaining to this subject matter are governed by the
 *  license agreement. The recipient of this software implicitly accepts
 *  the terms of the license.
 *  本软件文档资料是跨越速运集团有限公司的资产，任何人士阅读和
 *  使用本资料必须获得相应的书面授权，承担保密责任和接受相应的法律约束。
 *
 * ************************************************************************
 */
/**
  * <pre>
  * 作   者：liwei
  * 创建日期：2018-1-4
  * </pre>
  */
package com.kyexpress.common.hrinterview.provider.controller;

import com.kyexpress.common.hrinterview.api.bo.EmailBO;
import com.kyexpress.common.hrinterview.api.bo.EmployeeBO;
import com.kyexpress.common.hrinterview.api.model.Employee;
import com.kyexpress.common.hrinterview.api.model.User;
import com.kyexpress.common.hrinterview.provider.service.EmployeeService;
import com.kyexpress.common.hrinterview.provider.service.MailService;
import com.kyexpress.common.hrinterview.provider.service.UserService;
import com.kyexpress.common.hrinterview.provider.utils.EmailUtils;
import com.kyexpress.common.hrinterview.provider.utils.ErrorEnum;
import com.kyexpress.common.hrinterview.provider.utils.FileUtils;
import com.kyexpress.common.hrinterview.provider.utils.InterviewUtils;
import com.kyexpress.framework.annotation.PropertyFiltration;
import com.kyexpress.framework.model.Pagination;
import com.kyexpress.framework.model.ResponseData;
import com.kyexpress.framework.utils.ContextUtils;
import com.kyexpress.framework.utils.DateUtils;
import com.kyexpress.framework.utils.EncryptUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * <pre>
 * 表现层控制类
 * </pre>
 */
//@RefreshScope
@RestController
//@RequestMapping(value = "/hrinterview/user")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private UserService userService;
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private MailService mailService;
    @RequestMapping(value = "/login/info/{id}", method = RequestMethod.GET)
    @PropertyFiltration(clazz = Employee.class, excludes = {"updationDate", "enabledFlag"}, includes = {"*"})
    public ResponseData<User> loginInfo(@PathVariable("id") Long id) {
        ResponseData<User> result = new ResponseData<User>();

        User loginUser = InterviewUtils.loginUserMap.get(id.toString());
        String xuid = InterviewUtils.xuidMap.get(loginUser.getId().toString());
        loginUser.setXuid(xuid);
        return result;
    }

    /**
     * 判断是否登录
     * @return
     */
    @RequestMapping(value = "/isLogin", method = RequestMethod.POST)
    public boolean isLogin() {
        return InterviewUtils.isLogin();
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @PropertyFiltration(clazz = User.class, excludes = {"updationDate", "enabledFlag","createdBy","creationDate","updatedBy"}, includes = {"*"})
    public ResponseData<User> login(@RequestBody User user) {
        ResponseData<User> result = new ResponseData<User>();
        /****** 参数验证 *****/
        if(user.getUsername()  == null || user.getUsername().trim().length() == 0){
            ErrorEnum.UsernameNotNull.initResponseData(result);
            return result;
        }
        if(user.getPassword()  == null || user.getPassword().trim().length() == 0){
            ErrorEnum.PasswordNotNull.initResponseData(result);
            return result;
        }

        //业务逻辑
        User queryUser = new User();
        queryUser.setUsername(user.getUsername());
        List<User> userList = userService.selectAll(queryUser);
        if(userList == null || userList.size() == 0){
            ErrorEnum.UsernameNotExist.initResponseData(result);
            return result;
        }
        User loginUser = userList.get(0);
        if(loginUser.getEnabledFlag() != 1 ){
            ErrorEnum.UsernameNotExist.initResponseData(result);
            return result;
        }
        if(!loginUser.getPassword().equals(user.getPassword())){
            ErrorEnum.PasswordNotOk.initResponseData(result);
            return result;
        }

        //把用户信息保存到内存当中
        String token = EncryptUtils.md5(loginUser.getUsername()+ System.currentTimeMillis());
        String xuid = loginUser.getId().toString()+token;
        loginUser.setXuid(xuid);
        result.setData(loginUser).ok();
        InterviewUtils.xuidMap.put(loginUser.getId().toString(),xuid);
        InterviewUtils.loginUserMap.put(loginUser.getId().toString(),loginUser);
        return result;
    }

    /**
     * 邮件发送
     * @param bo
     * @return
     */
    @PropertyFiltration(clazz = EmailBO.class, excludes = {"updationDate"}, includes = {"*"})
    @RequestMapping(value = "/email/send", method = RequestMethod.POST)
    public ResponseData sendEmail(@RequestBody EmailBO bo ) {
        ResponseData result = new ResponseData();
        if(!InterviewUtils.isLogin()){
            ErrorEnum.UserNotLogin.initResponseData(result);
            return  result;
        }

        if(bo == null){
            ErrorEnum.EmailAccountNotNull.initResponseData(result);
        }
        /****** 参数验证 *****/
        if(bo.getReceiveMailAccount()  == null || bo.getReceiveMailAccount().trim().length() == 0){
            ErrorEnum.EmailAccountNotNull.initResponseData(result);
            return result;
        }
        if(bo.getReceiveMailNickname()   == null || bo.getReceiveMailNickname().trim().length() == 0){
            ErrorEnum.EmailNicknameNotNull.initResponseData(result);
            return result;
        }
        if(bo.getTitle()  == null || bo.getTitle().trim().length() == 0){
            ErrorEnum.EmailTitleNotNull.initResponseData(result);
            return result;
        }
        if(bo.getContent()  == null || bo.getContent().trim().length() == 0){
            ErrorEnum.EmailContentNotNull.initResponseData(result);
            return result;
        }
        if(bo.getTitle().trim().length() >50){
            ErrorEnum.EmailTitleLengthError.initResponseData(result);
            return result;
        }
        /*if(bo.getContent().trim().length()  >  1000){
            ErrorEnum.EmailContentLenghtError.initResponseData(result);
            return result;
        }*/
        //业务逻辑
        EmailUtils emailUtils = new EmailUtils();
        try {
            emailUtils.sendEmail(bo.getReceiveMailAccount(),bo.getReceiveMailNickname(),bo.getTitle(),bo.getContent());
        } catch (Exception e) {
            e.printStackTrace();
            ErrorEnum.EmailSendError.initResponseData(result);
            return result;
        }
        result.setData(bo).ok();
        return result;
    }
    @RequestMapping(value = "/batDownloan", method = RequestMethod.POST)
    public ResponseData<User> batDownloan(@PathVariable("employeeId") Long employeeId, HttpServletResponse response) {
        ResponseData result = new ResponseData();
        FileUtils fileUtils = new FileUtils();
        try {
            fileUtils.batDown(response);
        } catch (Exception e) {
            e.printStackTrace();
            ErrorEnum.ZipDownloanERROR.initResponseData(result);
            return result;
        }
        result.ok();
        return result;
    }

    /**
     * 列表查询
     * @param bo
     * @return
     */
    @RequestMapping(value = "/employee/list", method = RequestMethod.POST)
    @PropertyFiltration(clazz = Employee.class, excludes = {"updationDate", "enabledFlag","createdBy","creationDate","updatedBy"}, includes = {"*"})
    public ResponseData<Pagination<Employee>> list(@RequestBody EmployeeBO bo) {
        ResponseData<Pagination<Employee>> result = new ResponseData<>();
        if(!InterviewUtils.isLogin()){
            ErrorEnum.UserNotLogin.initResponseData(result);
            return  result;
        }

        // 0.输入参数检查
        if(bo == null){
            ErrorEnum.PaginationParameterError.initResponseData(result);
            return  result;
        }
        if(bo.getEmployee() == null){
            ErrorEnum.PaginationParameterError.initResponseData(result);
            return  result;
        }
        if (bo.getPage() < 1 || bo.getPageSize() < 1) {
            ErrorEnum.PaginationParameterError.initResponseData(result);
            return  result;
        }

        String userId = ContextUtils.get().getUser().getId();
        User loginUser = userService.get(Long.valueOf(userId));
        if(loginUser == null){
            ErrorEnum.UserNotLogin.initResponseData(result);
            return  result;
        }
        if(loginUser.getRoleid() != null && loginUser.getRoleid().toString().equals("2")){
            String department = loginUser.getDepartment();
            bo.getEmployee().setDepartment(department);
        }
        // 1.分页查询
        bo.getEmployee().setEnabledFlag(1L); // 未删除
        //看查询一个月内的记录
        Date startDate =org.apache.commons.lang3.time.DateUtils.addMonths(DateUtils.getDate(),-1);
        bo.setStartDate(DateUtils.toTimestamp(DateUtils.toString(startDate)));
        Pagination<Employee> pagination = Pagination.getInstance4BO(bo);
        try {
            employeeService.search(pagination);
            result.setData(pagination).ok();
        } catch (Exception e) {
            logger.error("ErrorModuleConfigController.list", e);
            result.responseCode(ErrorEnum.SystemError.getCode(), ErrorEnum.SystemError.getMsg());
        }
        return  result;
    }

    /**
     * offer发送
     * @param bo
     * @return
     */
    @RequestMapping(value = "/offer/send", method = RequestMethod.POST)
    public ResponseData sendOfferEmail(@RequestBody EmailBO bo) {
        ResponseData result = new ResponseData();
//        if(!InterviewUtils.isLogin()){
//            ErrorEnum.UserNotLogin.initResponseData(result);
//            return  result;
//        }
        Long employeeid = bo.getEmployeeid();
        String receiveMailAccount = bo.getReceiveMailAccount();
        String receiveMailNickname = bo.getReceiveMailNickname();
        String title = bo.getTitle();
        String content = bo.getContent();

        /****** 参数验证 *****/
        if(employeeid == null){
            ErrorEnum.FileEmployeeIdNotNull.initResponseData(result);
            return  result;
        }
        if(receiveMailAccount  == null || receiveMailAccount.trim().length() == 0){
            ErrorEnum.EmailAccountNotNull.initResponseData(result);
            return result;
        }
        if(receiveMailNickname  == null || receiveMailNickname.trim().length() == 0){
            ErrorEnum.EmailNicknameNotNull.initResponseData(result);
            return result;
        }
        if(title  == null || title.trim().length() == 0){
            ErrorEnum.EmailTitleNotNull.initResponseData(result);
            return result;
        }
        if(content  == null || content.trim().length() == 0){
            ErrorEnum.EmailContentNotNull.initResponseData(result);
            return result;
        }
        //业务逻辑
        EmailUtils emailUtils = new EmailUtils();
        try {
//            this.mailService.sendSimpleMail(receiveMailAccount,receiveMailNickname,title,content);
            this.mailService.sendHtmlMail(receiveMailAccount,receiveMailNickname,title,content);
            Employee employee = new Employee();
            employee.setId(employeeid);
            employee.setOffer(1);
            employeeService.update(employee);
        } catch (Exception e) {
            logger.error("UserController.sendOfferEmail", e);
            e.printStackTrace();
            ErrorEnum.EmailSendError.initResponseData(result);
            return result;
        }
        result.ok();
        return result;
    }
}